package com.rightsidetech.activity.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.rightsidetech.activity.dto.response.ActStoreCouponResp;
import com.rightsidetech.activity.mapper.ActCouponActivityMapper;
import com.rightsidetech.activity.mapper.ActCouponUsedRecordMapper;
import com.rightsidetech.activity.service.ActAgentAppCouponService;
import com.rightsidetech.commom.base.ResponseData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2022-01-11 11:24
 */
@Service("actAgentAppCouponService")
public class ActAgentAppServiceImpl implements ActAgentAppCouponService {

    @Resource
    private ActCouponActivityMapper actCouponActivityMapper;
    @Resource
    private ActCouponUsedRecordMapper actCouponUsedRecordMapper;

    @Override
    public ResponseData<List<ActStoreCouponResp>> findByStoreId(Long storeId, Long agentId) {
        List<ActStoreCouponResp> ActivityList = actCouponActivityMapper.selectStoredUsedActivity();
        if(ActivityList.isEmpty()){
            return ResponseData.success();
        }

        List<ActStoreCouponResp> activitys = new ArrayList<>();

        for(ActStoreCouponResp resp:ActivityList){
            List<Long> list = JSONArray.parseArray(resp.getUseScope(),Long.class);
            boolean flag = list.contains(agentId);
            if(!flag){
                continue;
            }
            //查找该门店优惠券使用数量
            int storeUserdCount = actCouponUsedRecordMapper.selectCountByActivityIdAndStoreId(resp.getActivityId(),storeId);

            Long remainCount = resp.getGetQuantity() - storeUserdCount;

            if(remainCount <= 0){
                remainCount = 0L;
            }
            resp.setRemainCount(remainCount);
            resp.setUseScope(null);
            resp.setTotalQuantity(resp.getTotalQuantity());
            resp.setGetQuantity(resp.getGetQuantity());

            if(remainCount != 0L){
                activitys.add(resp);
            }

        }

        return ResponseData.success(activitys);
    }
}
